package com.gopay.scheduler.job;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import com.gopay.common.order.dao.CommonQueryDAO;
import com.gopay.common.util.DateUtils;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.sms.client.GopaySMSHttpClient;
import com.gopay.sms.common.constants.SMSAppId;
import com.gopay.sms.common.domain.RequestVO;
import com.ibm.icu.math.BigDecimal;

/** 
 * @ClassName: CbRmbPersonalRemitCountSMSJob 
 * @Description: 个人汇款工作日/非工作日短信统计
 * @author b.zou
 * @date 2017-06-02  
 */

public class CbRmbPersonalRemitCountSMSJob extends GopayBaseJob {

    /* (非 Javadoc) 
     *  
     *   
     * @see com.gopay.scheduler.GopayBaseJob#doJobInternal() 
     */
    
    //日志
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    
    private @Value("#{webProperties['cbrmbPersonalRemitCountMobile']}") String mobile;
    
    @Resource(name = "commonQueryDAO")
    private CommonQueryDAO commonQueryDAO;
    
    @Override
    protected void doJobInternal() {
        
        //获取当前时间
        Date now=new Date();
        logger.info("======= CbRmbPersonalRemitCountSMSJob  BEGIN  ===========");
        Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        Date nowTime = c.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c2 = Calendar.getInstance();
        c2.add(Calendar.DAY_OF_MONTH, -1);
        Date beforeTime = c2.getTime();
        //前一天16:00
        Date yes1600 = new Date(beforeTime.getYear(), beforeTime.getMonth(), beforeTime.getDate(), 16, 00);
        //当天08:30
        Date today0830 = new Date(nowTime.getYear(), nowTime.getMonth(), nowTime.getDate(), 8, 30);
        //当天16:00
        Date today1600 = new Date(nowTime.getYear(), nowTime.getMonth(), nowTime.getDate(), 16, 00);

        Map<String, Object> params = new HashMap<String, Object>();
        
        //节假日判断
        if(isHoliday(now)){
            //如果为节假日，则每日8：30,16:00各统计一次汇款支付成功订单
            logger.info("======= CbRmbPersonalRemitCountSMSJob IT'S A HOLIDAY  ===========");
            if(hour == 8 && minute == 30){
                params.put("beginTime", sdf.format(yes1600));
                params.put("endTime", sdf.format(today0830));
                Map<String,String> result = this.getResult(params);
                this.sendMorningSMS(result);
            }else if(hour == 16 && minute == 00){
                params.put("beginTime", sdf.format(today0830));
                params.put("endTime", sdf.format(today1600));
                Map<String,String> result = this.getResult(params);
                this.sendAfternoonSMS(result);
            }else{
                logger.info("======= CbRmbPersonalRemitCountSMSJob IT'S HOLIDAY BUT NOT THE WORKING TIME  ===========");
            }
        }else{
            logger.info("======= CbRmbPersonalRemitCountSMSJob IT'S NOT A HOLIDAY  ===========");
            if(hour == 8 && minute == 30){
                params.put("beginTime", sdf.format(yes1600));
                params.put("endTime", sdf.format(today0830));
                Map<String,String> result = this.getResult(params);
                this.sendMorningSMS(result);
            }else{
                logger.info("======= CbRmbPersonalRemitCountSMSJob DOESN'T WORK IN THE WRONG TIME ===========");
                
            }
        }
    }
    
    /**
     * @Description: 统计前一天16:00PM至当天8:30AM支付成功的个人汇款(跨境汇款、留学汇款)统计总金额和总笔数并发送短信给运营人员  
     */
    protected void sendMorningSMS(Map<String,String> result){
        if("0".equals(result.get("totalCount"))||"0".equals(result.get("totalAmt"))){
            logger.info("======= CbRmbPersonalRemitCountSMSJob MORNING MESSAGE SENDING SUCCESS  ======= 支付成功的个人跨境汇款共0笔，总金额为0元,不发短信提醒！");
        }else{
            Calendar c = Calendar.getInstance();
            int year=c.get(Calendar.YEAR);
            int month=c.get(Calendar.MONTH)+1;
            int day=c.get(Calendar.DATE);
            
            String totalCount = result.get("totalCount");
            String totalAmt = result.get("totalAmt");
            sendSmsNotify(year+"年"+month+"月"+(day-1)+"日16:00 - "+year+"年"+month+"月"+day+"日8:30，支付成功的个人跨境汇款共"+totalCount+"笔，总金额为"+totalAmt+"元。");
            logger.info("======= CbRmbPersonalRemitCountSMSJob MORNING MESSAGE SENDING SUCCESS  ===========支付成功的个人跨境汇款共"+totalCount+"笔，总金额为"+totalAmt+"元。");
        }
    }
    
    /**
     * @Description: 统计当天8:30AM至16:00PM支付成功的个人汇款(跨境汇款、留学汇款)统计总金额和总笔数并发送短信给运营人员  
     */
    protected void sendAfternoonSMS(Map<String,String> result){
        if("0".equals(result.get("totalCount"))||"0".equals(result.get("totalAmt"))){
            logger.info("======= CbRmbPersonalRemitCountSMSJob MORNING MESSAGE SENDING SUCCESS  ======= 支付成功的个人跨境汇款共0笔，总金额为0元,不发短信提醒！");
        }else{
            Calendar c = Calendar.getInstance();
            int year=c.get(Calendar.YEAR);
            int month=c.get(Calendar.MONTH)+1;
            int day=c.get(Calendar.DATE);
            String totalCount = result.get("totalCount");
            String totalAmt = result.get("totalAmt");
            sendSmsNotify(year+"年"+month+"月"+day+"日8:30 - "+year+"年"+month+"月"+day+"日16:00，支付成功的个人跨境汇款共"+totalCount+"笔，总金额为"+totalAmt+"元。");
            logger.info("======= CbRmbPersonalRemitCountSMSJob AFRERNOON MESSAGE SENDING SUCCESS  ===========支付成功的个人跨境汇款共"+totalCount+"笔，总金额为"+totalAmt+"元。");
        }
    }
    
    /**
     * @Description: 获取符合条件的订单条数及总金额
     * @param params
     * @return 
     */
    protected Map<String,String> getResult(Map<String,Object> params){
        
        logger.info("-----跨境人民币统计个人汇款业务查询开始-----");
        
        Map<String,String> returnMap = new HashMap<>();
        String sql = "select count(1),sum(t1.mer_txn_amt)"
                + " from cps_gen_main_order t1"
                + " left join user_info t2 on t1.pay_cust_id=t2.cust_id"
                + " where t1.gopay_int_txn_cd in ('01724','01723') and t1.txn_sta_cd='30402' and t2.user_type='10'"
                + " and t1.gopay_txn_tm>=to_date(:beginTime,'yyyy-MM-dd hh24:mi:ss') and t1.gopay_txn_tm<to_date(:endTime,'yyyy-MM-dd hh24:mi:ss')" ;
        List<Object[]> list = commonQueryDAO.findBySql(sql, params);
        if(list!=null){
             String totalCount = list.get(0)[0]==null?"0":list.get(0)[0].toString();
             BigDecimal totalAmt=new BigDecimal(list.get(0)[1]==null?"0":list.get(0)[1].toString()).setScale(2); 
             returnMap.put("totalCount", totalCount);
             returnMap.put("totalAmt", totalAmt.toString());
        }else{
            returnMap.put("totalCount", "0");
            returnMap.put("totalAmt", "0");
            returnMap = null;
        }
        logger.info("-----跨境人民币统计个人汇款业务查询结束-----共有"+returnMap.get("totalCount")+"笔订单，总金额为"+returnMap.get("totalAmt"));
        return returnMap;
    }
    
    /**
     * 是否为节假日,暂时就用节假日表01类型
     * @return
     */
    public boolean isHoliday(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        String year = DateUtils.format(calendar.getTime(), "yyyy");
        String month = DateUtils.format(calendar.getTime(), "M");
        String day = DateUtils.format(calendar.getTime(), "d");
        
        StringBuilder sb = new StringBuilder();
        
        sb.append(" select t.year, t.month, t.holidays ");
        sb.append("   from holiday_information t ");
        sb.append("  where 1 = 1       ");
        sb.append("    and ','||t.holidays||',' like :holidays ");
        sb.append("    and t.month=:month ");
        sb.append("    and t.year=:year ");
        sb.append("    and t.holiday_type = '01' ");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("holidays", "%,"+day+",%");
        map.put("month", month);
        map.put("year", year);

        List<Object[]> rsList = commonQueryDAO.findBySql(sb.toString(), map);

        return rsList != null && rsList.size() > 0;
    }

    
    /**
     * 发送短信
     * @param mobileNo
     * @param smsType
     * @return
     */
    private void sendSmsNotify(String content){
        try {
            RequestVO req = new RequestVO();
            req.setAppId(SMSAppId._90000.value);
            req.setMobile(mobile);//如果发送多个手机号码时，可使用逗号进行隔开。
            req.setContent(content);
            GopaySMSHttpClient.getInstance().createVerificationCode(req);
        } catch (Exception e) {
           // e.printStackTrace();
            logger.error("跨境人民币统计个人汇款业务发送短信通知时异常", e);
        }
    }

}
